{
 "cells": [
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import csv\n",
    "import os\n",
    "import six\n",
    "\n",
    "os.chdir('.')"
   ],
   "id": "34eb1ff0cf45891c"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "import plotly as py\n",
    "import plotly.graph_objs as go\n",
    "py.offline.init_notebook_mode() # 初始化\n",
    "pyplot = py.offline.iplot   # 画图"
   ],
   "id": "dbf84e66c00fdf48"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "online_data = pd.read_csv('data.csv', encoding='ISO-8859-1', dtype={'CustomerId':str})  # 指定CustomerId为字符串类型\n",
    "online_data.head()  # 查看数据"
   ],
   "id": "e327fe5608413feb"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "type(online_data)   # 查看数据类型\n",
    "online_data.shape()   # 查看数据维度\n",
    "online_data.info()  # 查看数据信息\n",
    "online_data.describe()  # 查看数据描述"
   ],
   "id": "8b8710d6b502c857"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "online_data.isnull()    # 查看数据是否为空\n",
    "online_data.apply(lambda x: sum(x.isnull())/len(x),axis=0)    # 查看数据中每一列的缺失值比例\n",
    "df1 = online_data.dropna(how='any').copy()  # 哪一列有缺失就删去这一行"
   ],
   "id": "4ed6c64565425e72"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "df1['InvoiceDate'] = pd.to_datetime(df1['InvoiceDate'],errors='coerce') # 将InvoiceDate列转换为时间格式\n",
    "df1.info()"
   ],
   "id": "b28391289c5d668a"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "df1['InvoiceDate'] = df1['InvoiceDate'].dt.date # 将InvoiceDate列转换为日期格式\n",
    "df1.head()"
   ],
   "id": "844a239fd624351d"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 计算每个订单的金额\n",
    "df1['Price'] = df1.apply(lambda x: x.iloc[3] * x.iloc[5],axis=1)  # 计算总价格"
   ],
   "id": "f4e111a1f6a87f74"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 获取产品数量前十的国家\n",
    "df1[df1['Quantity'] < 0].head()\n",
    "df1[df1['Quantity'] < 0].shape()\n",
    "df1[df1['Quantity'] > 0].groupby('Country')['Quantity'].sum()   # 计算各个国家的产品数量\n",
    "quantity_first_10=df1[df1['Quantity'] > 0].groupby('Country')['Quantity'].sum().sort_values(ascending=False).head(10)"
   ],
   "id": "d47f954255f1b9d5"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 可视化\n",
    "trace_basic = [go.Bar(x=quantity_first_10.index.tolist(),y=quantity_first_10.values.tolist(),\n",
    "                      marker=dict(color='orange'),opacity=0.50)]\n",
    "layout = go.Layout(title='产品数量前十的国家',xaxis=dict(title='国家'))\n",
    "figure_basic = go.Figure(data=trace_basic,layout=layout)\n",
    "pyplot(figure_basic)"
   ],
   "id": "963e89ceaafc29c1"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 获取销售额前十的国家\n",
    "trans = df1[df1['Quantity']>0].groupby('Country')['Price'].sum().sort_values(ascending=False).head(10)\n",
    "trace_basic = [go.Bar(x=trans.index.tolist(),y=trans.values.tolist(),\n",
    "                      marker=dict(color='orange'),opacity=0.50)]\n",
    "layout = go.Layout(title='销售额前十的国家',xaxis=dict(title='国家'))\n",
    "figure_basic = go.Figure(data=trace_basic,layout=layout)\n",
    "pyplot(figure_basic)"
   ],
   "id": "4bfa87560ff688b1"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 哪些月份销售较佳\n",
    "df1['month'] = pd.to_datetime(df1['InvoiceDate']).dt.month  # 将InvoiceDate列转换为月份格式\n",
    "df_month = df1[df1['Quantity'] > 0].groupby('month')['Quantity'].sum().sort_values(ascending=False).head(12)   # 计算各个月份销售额\n",
    "import seaborn as sns\n",
    "sns.set(style=\"whitegrid\", context='notebook',font_scale=1.2)\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "df_month.plot(kind='bar',title='各月份销售额')\n",
    "plt.xticks(rotation=45)"
   ],
   "id": "91ab3525190821aa"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 平均客单价\n",
    "# 按订单量计算\n",
    "sumPrice = df1[df1['Quantity'] > 0]['Price'].sum()\n",
    "countId = df1[df1['Quantity'] > 0]['InvoiceNo'].count().shape\n",
    "avgPrice = sumPrice/countId[0]\n",
    "# 按用户数量计算\n",
    "user_count = df1[df1['Quantity'] > 0].groupby('CustomerId').count().shape\n",
    "avgPrice1 = sumPrice/user_count[0]"
   ],
   "id": "5b1e888337dcfbfa"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "# 用户消费行为分析\n",
    "customer = df1[df1['Quantity'] > 0].groupby('CustomerId').agg({'Price':'sum','InvoiceNo':'nunique','Quantity':'sum'})\n",
    "customer.describe()"
   ],
   "id": "87faf4dc16b3f771"
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}
